package com.wjw.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//import net.sf.json.JSON;
//import net.sf.json.xml.XMLSerializer;
/**
 * @desc 通过正则表达式提取xml内容
 * @author wjw
 * @date 2016年11月29日下午5:51:34
 */
public class XMLUtil {

	/**
	 * 通过DOM4J将xml字符串转换成json  复杂内容解析
	 * @param xmlString
	 * @return
	 */
	public static String xml2json(String xmlString) {
		// XMLSerializer xmlSerializer = new XMLSerializer();
		// JSON json = xmlSerializer.read(xmlString);
		// return json.toString();
		return null;
	}
	/**
	 * 通过正则表达式解读取制定DOM内容
	 * @param xmlContent
	 * @return
	 */
	public static List<String> getContext(String xmlContent) {
		List<String> resultList = new ArrayList<String>();
		Pattern p = Pattern.compile(">([^</]+)</");// 正则表达式 commend by
		Matcher m = p.matcher(xmlContent);
		while (m.find()) {
			resultList.add(m.group(1));
		}
		return resultList;
	}

	public static void main(String[] args) {
		String text = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" 
					+ "<SubmitResult xmlns=\"http://106.ihuyi.cn/\">"
						+ "<code>2</code>" 
						+ "<msg>提交成功</msg>" 
						+ "<smsid>298313649</smsid>" 
					+ "</SubmitResult>";

		List<String> list = getContext(text);
		System.out.println(list);
		
		String data = text.toLowerCase();
		Pattern pattern2 = Pattern.compile("<submitresult xmlns=\"http://106.ihuyi.cn/\">(.*?)</submitresult>");
		Matcher matcher2 = pattern2.matcher(data);
		//遍历匹配到的集合
		while (matcher2.find()) {
			int i = 1;
			String data1 = matcher2.group(i);
			System.out.println("group："+i+"\t\t"+getParameter(data1, "code"));
			System.out.println("group："+i+"\t\t"+getParameter(data1, "msg"));
			System.out.println("group："+i+"\t\t"+getParameter(data1, "smsid"));
			i++;
		}
	}
	
	public static String getParameter(String data, String para) {
		String result = "";
		StringBuffer reStr = new StringBuffer();
		reStr.append("<");
		reStr.append(para);
		reStr.append(">");
		reStr.append("(.*?)");
		reStr.append("</");
		reStr.append(para);
		reStr.append(">");
		Pattern pattern = Pattern.compile(reStr.toString());
		Matcher matcher = pattern.matcher(data);
		if (matcher.find()) {
			result = matcher.group(1);
		}
		return result;
	}
}
